import React from 'react';
import PropTypes from 'prop-types';
import {Card, Row, Col, Table, Button, Spin, Divider} from 'antd';
import {PERMISSION} from './constants';
import {DATETIME_FORMAT, TABLE, DATE_FORMAT, FILES_API} from '../constants';
import {hasPermissions} from './utils';
import {injectIntl, formatMessage} from './intl';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {currency, goodWillType, claimApprovedResult, goodWillDetailType, fileType} from '../Enum';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {abandonOrder, submitOrder, getDetail} from './api';
import ImageUpload from './ImageUpload';
import routes from './routes';
import styles from './style.css';
const {Description} = DescriptionList;

export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        details: [],
        approveResults: [],
        athDetails: [],
        data: {}
    };

    componentDidMount() {
        this.getDetailInfo();
    }

    getDetailInfo = () => {
        this.setState({loading: true});
        getDetail(this.props.id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        approveResults: res.data.approveResults,
                        athDetails: res.data.athDetails,
                        details: res.data.details,
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }

    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        abandonOrder(this.state.data.id, this.state.data.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickSubmit = () => {
        this.setState({loading: true});
        submitOrder(this.state.data.id, this.state.data.rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    render() {
        const operations = [];
        const {data = {}, athDetails = []} = this.state;
        const {id, permissions, isDealerUser, onCancel} = this.props;
        const athDetailsTuPhoto = athDetails.find(v => v.fileType === fileType.图片) || {};
        const athDetailsTuFile = athDetails.find(v => v.fileType === fileType.文件) || {};
        if(hasPermissions(permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(permissions, PERMISSION.confirm) && hasPermissions(data.options, PERMISSION.confirm))
            operations.push(<Button key="confirm" href={`#${routes.confirm.format(id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.opeation',
                    defaultMessage: '确认'
                })
            }</Button>);
        if(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(permissions, PERMISSION.submit) && hasPermissions(data.options, PERMISSION.submit))
            operations.push(<WrappedPopconfirm
                key="submit"
                id={id}
                placement="topLeft"
                onConfirm={this.onClickSubmit}
                title={formatMessage({
                    id: 'detailPanel.validate.submit',
                    defaultMessage: '是否确认提交？'
                })}>
                <Button key="submit" size="small">{
                    formatMessage({
                        id: 'detailPanel.submit',
                        defaultMessage: '提交'
                    })
                }</Button>
            </WrappedPopconfirm>);
        const columns = [
            {
                title: formatMessage({
                    id: 'detailPanel.type',
                    defaultMessage: '类型'
                }),
                dataIndex: 'type',
                render: text => conventEnumValueToString(goodWillDetailType, text)
            },
            {
                title: formatMessage({
                    id: 'detailPanel.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
            },
            {
                title: formatMessage({
                    id: 'detailPanel.name',
                    defaultMessage: '名称'
                }),
                dataIndex: 'name',
            },
            {
                title: formatMessage({
                    id: 'detailPanel.usedQty',
                    defaultMessage: '数量'
                }),
                dataIndex: 'usedQty',
            },
            {
                title: formatMessage({
                    id: 'detailPanel.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                render: text => formatAmount(text)
            },
            {
                title: formatMessage({
                    id: 'detailPanel.totalPrice',
                    defaultMessage: '费用合计'
                }),
                dataIndex: 'totalPrice',
                render: text => formatAmount(text)
            },
        ];
        const columResults = [{
            title: formatMessage({
                id: 'detailPanel.approverName',
                defaultMessage: '审核人'
            }),
            dataIndex: 'approverName'
        },
        {
            title: formatMessage({
                id: 'detailPanel.approveComment',
                defaultMessage: '意见'
            }),
            dataIndex: 'approveComment'
        },
        {
            title: formatMessage({
                id: 'detailPanel.approvedResult',
                defaultMessage: '审核结果'
            }),
            dataIndex: 'approvedResult',
            render: text => conventEnumValueToString(claimApprovedResult, text)
        },
        {
            title: formatMessage({
                id: 'detailPanel.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }];
        return (
            <div className={styles.detail}>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{
                            formatMessage({
                                id: 'detailPage.card.tradeMethodmessage',
                                defaultMessage: '基本信息'
                            })
                        }</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPage.data.code',
                                defaultMessage: '编号',
                            })}>{data.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.brand',
                                defaultMessage: '品牌'
                            })}>{`(${data.brandCode})${data.brandName}`}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}</Description>
                            {!isDealerUser && <Description term={formatMessage({
                                id: 'detailPage.data.type',
                                defaultMessage: '归类'
                            })}>{conventEnumValueToString(goodWillType, data.type)}</Description>}
                            <Description term={formatMessage({
                                id: 'detailPage.data.country',
                                defaultMessage: '国家'
                            })}>{data.country}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.VIN',
                                defaultMessage: 'VIN'
                            })}>{data.vin}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.productCategoryCode',
                                defaultMessage: '车型'
                            })}>{data.productCategoryCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.engineCode',
                                defaultMessage: '发动机号'
                            })}>{data.engineCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.transmissionSn',
                                defaultMessage: '变速箱号'
                            })}>{data.transmissionSn}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.data.salesDate',
                                defaultMessage: '实销日期'
                            })}>{formatDateTime(data.salesDate, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.mileage',
                                defaultMessage: '行驶里程'
                            })}>{data.mileage}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.tel',
                                defaultMessage: '联系电话'
                            })}>{data.tel}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.customer',
                                defaultMessage: '客户名称'
                            })}>{data.customer}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.faultItem',
                                defaultMessage: '故障代码'
                            })}>({data.faultItemCode}) {data.faultItemName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.opinion',
                                defaultMessage: '申请原因'
                            })}>{data.opinion}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.productCategoryCode',
                                defaultMessage: '车型'
                            })}>{data.productCategoryCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.totalFee',
                                defaultMessage: '申请金额'
                            })}>{formatAmount(data.totalFee)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.createTime',
                                defaultMessage: '申请时间'
                            })}>{formatDateTime(data.createTime, DATE_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPage.data.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}</Description>
                        
                        </DescriptionList>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'detailPage.details.title',
                            defaultMessage: 'GoodWill清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="id"
                            columns={columns}
                            pagination={false}
                            dataSource={this.state.details}
                            {...TABLE} />
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.fileAth',
                            defaultMessage: '附件清单'
                        })}>
                        {athDetails && athDetails.length > 0
                            ? <div>
                                {
                                    (athDetailsTuPhoto || athDetailsTuFile) &&
                                        <DescriptionList title={formatMessage({
                                            id: 'detailPanel.card.attachmentTu',
                                            defaultMessage: '图片资料附件'
                                        })} size="large">
                                            {(athDetailsTuPhoto.attachments && athDetailsTuPhoto.attachments.length > 0) &&
                                            <div><ImageUpload fileList={athDetailsTuPhoto.attachments} isUpload={false}/>
                                                <Divider /></div>}
                                            {(athDetailsTuFile.attachments && athDetailsTuFile.attachments.length > 0) &&
                                                athDetailsTuFile.attachments.map(item => (<Description key={item.fileId}>
                                                    {item.filePath ? <a onClick={this.onClickDownload} key={item.fileId}
                                                        data-id={item.filePath} data-applyid={item.fileName}>
                                                        {item.fileName}</a> : <a icon="download" download
                                                        href={`${FILES_API.files}/${item.fileId}`} size="small">{item.fileName}</a>}
                                                </Description>))}
                                        </DescriptionList>
                                }
                            </div>
                            : formatMessage({
                                id: 'detailPanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}
                    </Card>
                    <Card title={formatMessage({
                        id: 'detailPanel.table.confirmResultdetails',
                        defaultMessage: '操作履历'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columResults}
                            rowKey="id"
                            pagination={false}
                            dataSource={this.state.approveResults}
                            {...TABLE} />
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={onCancel}>{formatMessage({
                            id: 'detailPanel.btn.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
            
        );
    }
}

DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    history: PropTypes.object,
    isDealerUser: PropTypes.bool,
    successReturn: PropTypes.func,
    onCancel: PropTypes.func,
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    id: props.id,
    permissions: getPermissions(state),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
});
const mapDispatchToProps = (dispatch, props) => ({
    onCancel: () => props.history.push(routes.query.url()),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
